import { useMutation, useQueryClient } from '@tanstack/react-query';
import { Form, Input, message, Modal } from 'antd';
import React from 'react';

import api from '@/apis/api';
import { Logger } from '@/components/useLogger';

interface KeyDelteModalProps {
  keyIndex: number | undefined;
  keyType: number | undefined;
  visible: boolean;
  setVisible: (visible: boolean) => void;
  total: number;
  page: number;
  pageSize: number;
  setPage: (page: number) => void;
}

const KeyDelteModal: React.FC<KeyDelteModalProps> = ({
  keyIndex,
  keyType,
  visible,
  setVisible,
  total,
  page,
  pageSize,
  setPage,
}) => {
  const [form] = Form.useForm();

  const queryClient = useQueryClient();

  const DeleteKeyLog = useMutation({
    mutationFn: (params: any) => api.DeleteKeyLog(params),
    onSuccess: (res: any) => {
      if (res?.success === false) {
        Logger(res?.message);
        message.error(`删除失败，${res?.message}`);
      } else {
        message.success('删除成功');
        if (total && page > total / pageSize && total % pageSize === 1 && page > 1) {
          setPage(page - 1);
        }
      }
    },
    onError: (error: any) => {
      Logger(error);
      message.error('删除失败');
    },
    onSettled: () => queryClient.invalidateQueries({ queryKey: ['getKeyManageData'] }),
    mutationKey: ['getKeyManageData'],
  });

  const handleDeleteOk = async () => {
    await form.validateFields();
    const pinCode = form.getFieldValue('pinCode');
    DeleteKeyLog.mutate({
      key_type: keyType,
      key_index: keyIndex,
      pincode: pinCode ?? '',
    });
    form.resetFields();
    setVisible(false);
  };
  const handleDeleteCancel = () => {
    form.resetFields();
    setVisible(false);
  };

  return (
    <>
      <Modal
        title="删除密钥"
        open={visible}
        onOk={handleDeleteOk}
        onCancel={handleDeleteCancel}
        cancelText="取消"
        okText="确定"
        destroyOnClose
        // okButtonProps={{ disabled: localINFO.getRoleId() !== 1 }}
      >
        <Form
          form={form}
          preserve={false}
          labelCol={{ span: 8 }}
          wrapperCol={{ span: 16 }}
          style={{ maxWidth: 600, marginTop: 24, marginBottom: 24, width: 450 }}
          autoComplete="off"
        >
          {keyType !== 5 && (
            <Form.Item
              label="密钥访问控制码"
              name="pinCode"
              rules={[{ required: keyType !== 5, message: '请输入密钥访问控制码！' }]}
              style={{ marginBottom: 0 }}
            >
              <Input.Password placeholder="请输入pinCode" autoComplete="new-password" />
            </Form.Item>
          )}
          {keyType === 5 && <p style={{ marginLeft: 24 }}>您确定要删除该条密钥吗？</p>}
        </Form>
      </Modal>
    </>
  );
};

export default KeyDelteModal;
